const router = require('koa-router')();

const model = require("../../model/books.js");
const msg = require("../../model/msgs.js");
const mongoose = require("mongoose");

router.prefix('/books');


let obj = {
    name: '雪中悍刀行',
    // author: '烽火戏诸侯',
    // num: 300,
    // desc: '雪中之后无江湖',
    // type: ['武侠', '江湖'],
}

let obj2 = {
    author: '王林',
    sex: '男',
    age: 22,
    city: '北京'
}


router.get('/msg', async ctx => {
    let data = await msg.create(obj2)

    send(ctx, data)
})

router.get('/add', async ctx => {
    let data2 = await msg.create({
        author: '王林',
        sex: '男',
        age: 22,
        city: '北京'
    })

    let data = await model.create({
        book_id: data2._id,
        name: '雪中悍刀行',
        author: '烽火戏诸侯',
        num: 300,
        desc: '雪中之后无江湖',
        type: ['武侠', '江湖'],
    })
    
    send(ctx, data)
})


router.get('/remove', async ctx => {
    let data = await model.findByIdAndRemove('5c4ac57457f25a131965f1d9')

    send(ctx, data)
})






router.get('/find', async ctx => {
    const condition = {
        type: '都市'
    }

    let data = await model.find({name: '雪中悍刀行'})
    send(ctx, data)
})








router.get('/modify', async ctx => {
    const doc = {
        $pull: {type: '重生'}
    }

    let data = await model.update({name: '俗人回档'}, doc)

    send(ctx, data)
})
























// 查
router.get('/', async ctx => {
    let data = await model.find({})

    send(ctx, data)
})

router.get('/:id', async ctx => {
    let data = await model.findById(ctx.params.id)

    send(ctx, data)
})

// 增
router.post('/', async ctx => {
    
    const obj = await model.findOne({name: ctx.request.body.name})
    if (obj) {
        sendError(ctx, 204, '不能重复添加')
    } else {
        let data = await model.create(ctx.request.body)
        send(ctx, data)
    }
})

// 改
router.put('/', async ctx => {
    let data = await model.create({})

    send(ctx,'100')
})

// 删
router.delete('/', async ctx => {
    let data = await model.find().remove()

    send(ctx, data)
})




function send(ctx, data) {
    ctx.body = {
        code: 200,
        msg: '请求成功',
        data,
    }
}

function sendError(ctx, code = 204, msg = '无数据', data = null) {
    ctx.body = {
        code,
        msg,
        data,
    }
}

module.exports = router;

